package com.sky.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.Result.PageResult;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.exception.CustomException;
import com.sky.mapper.UserMapper;
import com.sky.model.dto.UserDTO;
import com.sky.model.dto.UserPageQueryDTO;
import com.sky.model.entity.User;
import com.sky.model.vo.UserVO;
import com.sky.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     * @param username
     * @param password
     */
    public void register(String username, String password) {

        //判断用户是否已经存在
        User user = userMapper.findByUsername(username);
        if (user != null) {
            throw new CustomException(MessageConstant.USER_EXIST);
        }
        LocalDateTime createTime = LocalDateTime.now();
        userMapper.register(username, password, createTime);
    }

    /**
     * 用户登录
     * @param username
     * @param password
     */
    @Override
    public User login(String username, String password) {
       User user=userMapper.findUser(username,password);
        if (user == null) {
            throw new CustomException(MessageConstant.USER_NOT_EXIST);
        }
        return user;
        }

    /**
     * 修改用户信息
     * @param userDTO
     */
    @Override
    public void update(User userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        if (user.getId() == null) {
            //获取用户id
            user.setId(BaseContext.getCurrentId());
        }

        //修改用户信息
        userMapper.update(user);
    }

    /**
     * 用户分页查询
     * @param userPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(UserPageQueryDTO userPageQueryDTO) {
        // 计算分页的偏移量和限制条数
        int offset = (userPageQueryDTO.getPage() - 1) * userPageQueryDTO.getPageSize();
        int limit = userPageQueryDTO.getPageSize();

        // 获取查询结果
        List<UserVO> userList = userMapper.pageQuery(userPageQueryDTO.getName(), offset, limit);

        // 获取总记录数
        long total = userMapper.countUsers(userPageQueryDTO.getName());

        // 返回分页结果
        return new PageResult(total, userList);
    }

    /**
     * 新增用户
     * @param userDTO
     */
    @Override
    public void save(UserDTO userDTO) {
    userMapper.save(userDTO);
    }

    /**
     * 批量启用禁用用户
     * @param ids
     */
    @Override
 @Transactional
public void startOrstops(List<Long> ids) {
    if (ids.isEmpty()) {
        throw new CustomException(MessageConstant.ID_LIST_EMPTY);
    }

    // Get the status of the first user
    Long firstId = ids.get(0);
    User firstUser = userMapper.findById(firstId);
    int firstStatus = firstUser.getStatus();

    // Compare the status of other users, if not consistent, throw an error
    for (Long id : ids) {
        User user = userMapper.findById(id);
        if (user.getStatus() != firstStatus) {
            throw new CustomException(MessageConstant.STATUS_MISMATCH);
        }
    }

    // Determine the new status value, 0 for disabled, 1 for enabled
    Integer newStatus = (firstStatus == 1) ? 0 : 1;

    // Update the status of all users
    for (Long id : ids) {
        User user = new User();
        user.setId(id);
        user.setStatus(newStatus);
        userMapper.update(user);
    }
}

    /**
     * 批量删除用户
     * @param ids
     */
    @Override
    public void delete(List<Long> ids) {
        if (ids.isEmpty()) {
            throw new CustomException(MessageConstant.ID_LIST_EMPTY);
        }
        // 判断当前用户是否能够删除 - 是否存在启用的用户
        for (Long id : ids) {
            User user = userMapper.findById(id);
            if (user.getStatus() == MessageConstant.ENABLE) {
                // 当前用户处于启用状态
                throw new CustomException(MessageConstant.USER_ENABLED);
            }
        }
        // 删除所有用户
        for (Long id : ids) {
            userMapper.deleteById(id);
        }
    }

    @Override
    public UserVO info() {
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.findById(userId);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }
}

